<?php


 


class MongoApi extends ApiBase{

	private static $handle = null;
	private static $conf = null;


	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();

		if(is_null(self::$handle)){

			$conf = n_confGet('mongo');
			
			if(!$conf['state']){
				throw new PException("conf:读取失败");
			}
			
			self::$conf = $conf['data'];
		}

		self::$handle['master'] = $this->db001;
	}
	

	
	public function __get($key){
		
		if(isset(self::$handle['master'])){
			return self::$handle['master'];
		}
		
		if(!isset(self::$conf[$key])){
			throw new PException("找不到数据库配置:{$key}");
		}
		
		
		self::$handle['master'] = new MongoDriver(self::$conf[$key]);
				
		return self::$handle['master'];		
	}

	/**
	 * 
	 * 
	 * 
	 * @param 		string $dbname
	 * @return 		
	 */
	public function cnameAbsolute($cname){

		self::$handle['master'] = $this->db001;

		self::$handle['master']->useDb($cname);
		return self::$handle['master'];
	}

	/*
	*	@function: 切换不同的server
	*	@param: server name(db001, db002)
	*	@return: server的句柄
	*/
	public function switchMac($MacName) {

		if($MacName == 'db001'){
			if(isset(self::$handle['master'])){
				return self::$handle['master'];
			}else{
				if(!isset(self::$conf[$MacName])){
					throw new PException("找不到数据库配置:{$MacName}");
				}

				self::$handle['master'] = new MongoDriver(self::$conf[$MacName]);
				
				return self::$handle['master'];
			}
			
		}

		if(isset(self::$handle[$MacName])){
			return self::$handle[$MacName];
		}

		if(!isset(self::$conf[$MacName])){
			throw new PException("找不到数据库配置:{$MacName}");
		}

		self::$handle[$MacName] = new MongoDriver(self::$conf[$MacName]);
				
		return self::$handle[$MacName];	
	}

}